package com.module.overview.ui.cardHistoryDetails.provider

import android.graphics.Typeface
import android.widget.TextView
import com.chad.library.adapter.base.provider.BaseItemProvider
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.common.app.data.bean.KeyPre
import com.common.app.data.bean.overView.HistoryDetailsModel
import com.common.app.utls.TimeUtils
import com.common.base.app.extras.doOnIOThread
import com.common.base.app.extras.doOnUiThread
import com.common.base.app.extras.no
import com.common.base.app.extras.yes
import com.common.base.utils.AppUtils
import com.common.base.utils.JsonUtils
import com.common.base.utils.MathUtil
import com.common.base.utils.SpUtilsManagement
import com.common.base.utils.SpanUtils
import com.common.base.utils.ViewUtils
import com.module.ble.repo.UserCalorieRepo
import com.module.ble.repo.UserStepsRelatedRecordRepo
import com.module.ble.utils.AllCardTypeConfig
import com.module.ble.utils.common48DataConvert
import com.module.ble.utils.common48DataConvertByStepsRelatedRecord
import com.module.ble.widget.CandlestickChart
import com.module.overview.R

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2025/7/14
 *
 * 描述：活动-卡路里卡片
 *
 * 修订历史：完成度100%
 *
 */
class OvActivityCalorieCardProvider(time:Long,
    override val itemViewType: Int = AllCardTypeConfig.TYPE_CARD_ACTIVITY_CALORIE,
    override val layoutId: Int = R.layout.overview_activity_calorie_crad_provider
) : BaseItemProvider<HistoryDetailsModel>() {

    private var curTime = time

    private var candlestickChart: CandlestickChart? = null
    private var tvCalorie: TextView? = null

    var hrSpliceHint = ViewUtils.getString(R.string.common_calorie_splice)

    init {
    }

    override fun convert(helper: BaseViewHolder, item: HistoryDetailsModel) {
        // 设置Y轴阶段
        candlestickChart?.setYAxisStages(
            floatArrayOf(0f, 50f, 100f), // 阶段分界点
        )

        getTheDayCalorieData()
    }


    override fun onViewHolderCreated(viewHolder: BaseViewHolder, viewType: Int) {
        tvCalorie = viewHolder.getView(R.id.tvCalorie)
        candlestickChart = viewHolder.getView(R.id.candlestickChart)
        candlestickChart?.setBarRounding(enableTop = true, enableBottom = false)

        // 设置触摸监听
        candlestickChart?.setOnBarTouchListener(object : CandlestickChart.OnBarTouchListener {

            override fun onBarTouched(
                index: Int,
                minValue: Float,
                maxValue: Float,
                timeLabel: String,
                extStr: String
            ) {
                // 处理触摸事件
//                Log.d("CandlestickChart", "触摸到柱子: 索引=$barIndex,触摸到: $timeLabel, 值: $minValue")
                SpanUtils.create()
                    .addSection(if(maxValue > -1) maxValue.toInt().toString() else "0")
//                    .addSection(hrSplice)
                    .addForeColorSection(hrSpliceHint, ViewUtils.getColor(R.color.c_7f7f7f))
                    .setAbsSize(hrSpliceHint, 14)
                    .setStyle(hrSpliceHint, Typeface.NORMAL)
                    .showIn(viewHolder.getView(R.id.tvTouchValue))

                candlestickChart?.let {
                    viewHolder.setText(R.id.tvTouchValueHint,"${TimeUtils.getHourMinute(it.getData()[index].createdTime)}-${TimeUtils.getHourMinute(it.getData()[index].endTime)}")
                }

                viewHolder.setVisible(R.id.totalTouchValue, true)
            }

            override fun onAverageLineTouched(
                index: Int,
                minValue: Float,
                maxValue: Float,
                timeLabel: String,
                extStr: String
            ) {
            }

            override fun onTouchReleased() {
                // 处理触摸释放事件
                viewHolder.setVisible(R.id.totalTouchValue, false)
            }
        })
        super.onViewHolderCreated(viewHolder, viewType)
    }

    /**
     * 获取当天卡路里信息
     */
    fun getTheDayCalorieData(){
        if (curTime <=0) return

        doOnIOThread {
            UserCalorieRepo.instance.findByOneDay(curTime)?.let { originalListIt->
                if (originalListIt.isNullOrEmpty()) return@doOnIOThread

//                val listItStr = JsonUtils.toJson(originalListIt)

                var totalCalorie = 0L

                val groupedData = common48DataConvert(doSum = true,curTime=curTime, originalList=originalListIt)
                groupedData.forEach { beanIt->
                    totalCalorie += beanIt.mValue.toInt()
                }

                // 直接获取最大的mValue值
                val maxValue = groupedData.maxOfOrNull { it.mValue } ?: 0f

                doOnUiThread {

                    tvCalorie?.text = totalCalorie.toString()

                    // 设置Y轴阶段
                    candlestickChart?.setYAxisStages(
                        floatArrayOf(0f, ((MathUtil.divInt(maxValue.toDouble(), 2.00)).toFloat()), maxValue.toInt().toFloat()), // 阶段分界点
                    )

                    //  通知图表更新数据
                    candlestickChart?.setData(groupedData)
                }
            }
        }
    }
}